import { ref, reactive } from 'vue'

// 手续费设置接口
export interface ServiceFeeSetting {
    id: string
    type: 'B' | 'C' // 会员类型
    site: string // 站点标识
    minAmount: number | null
    maxAmount: number | null
    fee: number
    remark?: string
}

// 服务费率设置接口
export interface ServiceRateSetting {
    id: string
    site: string
    rate: number
    remark?: string
}

// 保证金比例设置接口
export interface DepositRateSetting {
    id: string
    site: string
    rate: number
    remark?: string
}

// 基础设置管理服务
class BaseSettingsService {
    // 手续费设置列表
    private serviceFeeSettings = ref<ServiceFeeSetting[]>([])

    // 服务费率设置列表
    private serviceRateSettings = ref<ServiceRateSetting[]>([])

    // 保证金比例设置列表
    private depositRateSettings = ref<DepositRateSetting[]>([])

    // 初始化基础设置
    init() {
        // 从localStorage加载设置
        this.loadFromStorage()
    }

    // 从localStorage加载设置
    private loadFromStorage() {
        try {
            const serviceFees = localStorage.getItem('baseSettings_serviceFees')
            if (serviceFees) {
                this.serviceFeeSettings.value = JSON.parse(serviceFees)
            } else {
                // 默认手续费设置 - 与基础设置收费管理页面保持一致
                this.serviceFeeSettings.value = [
                    {
                        id: 'default_b_1',
                        type: 'B',
                        site: '煤炉',
                        minAmount: 0,
                        maxAmount: 10000,
                        fee: 200,
                        remark: 'B端客户煤炉平台0-10000日元区间手续费'
                    },
                    {
                        id: 'default_b_2',
                        type: 'B',
                        site: '煤炉',
                        minAmount: 10000,
                        maxAmount: 20000,
                        fee: 300,
                        remark: 'B端客户煤炉平台10000-20000日元区间手续费'
                    },
                    {
                        id: 'default_b_3',
                        type: 'B',
                        site: '煤炉',
                        minAmount: 30000,
                        maxAmount: null,
                        fee: 500,
                        remark: 'B端客户煤炉平台30000日元以上区间手续费'
                    },
                    {
                        id: 'default_c_1',
                        type: 'C',
                        site: '雅虎日拍',
                        minAmount: 0,
                        maxAmount: 10000,
                        fee: 200,
                        remark: 'C端客户雅虎日拍0-10000日元区间手续费'
                    }
                ]
            }

            const serviceRates = localStorage.getItem('baseSettings_serviceRates')
            if (serviceRates) {
                this.serviceRateSettings.value = JSON.parse(serviceRates)
            } else {
                // 如果没有保存的数据，添加一些默认的服务费率设置
                this.serviceRateSettings.value = [
                    {
                        id: 'default_service_rate_1',
                        site: '煤炉',
                        rate: 3.5,
                        remark: '煤炉默认服务费率'
                    },
                    {
                        id: 'default_service_rate_2',
                        site: '雅虎日拍',
                        rate: 4.0,
                        remark: '雅虎日拍默认服务费率'
                    },
                    {
                        id: 'default_service_rate_3',
                        site: '雅虎闲置',
                        rate: 3.8,
                        remark: '雅虎闲置默认服务费率'
                    },
                    {
                        id: 'default_service_rate_4',
                        site: '乐天闲置',
                        rate: 4.2,
                        remark: '乐天闲置默认服务费率'
                    }
                ]
            }

            const depositRates = localStorage.getItem('baseSettings_depositRates')
            if (depositRates) {
                this.depositRateSettings.value = JSON.parse(depositRates)
            } else {
                // 如果没有保存的数据，添加一些默认的保证金比例设置
                this.depositRateSettings.value = [
                    {
                        id: 'default_deposit_rate_1',
                        site: '煤炉',
                        rate: 10.0,
                        remark: '煤炉默认保证金比例'
                    },
                    {
                        id: 'default_deposit_rate_2',
                        site: '雅虎日拍',
                        rate: 12.0,
                        remark: '雅虎日拍默认保证金比例'
                    },
                    {
                        id: 'default_deposit_rate_3',
                        site: '雅虎闲置',
                        rate: 11.0,
                        remark: '雅虎闲置默认保证金比例'
                    },
                    {
                        id: 'default_deposit_rate_4',
                        site: '乐天闲置',
                        rate: 13.0,
                        remark: '乐天闲置默认保证金比例'
                    }
                ]
            }
        } catch (error) {
            console.error('加载基础设置失败:', error)
        }
    }

    // 保存到localStorage
    private saveToStorage() {
        try {
            localStorage.setItem('baseSettings_serviceFees', JSON.stringify(this.serviceFeeSettings.value))
            localStorage.setItem('baseSettings_serviceRates', JSON.stringify(this.serviceRateSettings.value))
            localStorage.setItem('baseSettings_depositRates', JSON.stringify(this.depositRateSettings.value))
        } catch (error) {
            console.error('保存基础设置失败:', error)
        }
    }

    // 获取手续费设置
    getServiceFeeSettings(type?: 'B' | 'C', site?: string): ServiceFeeSetting[] {
        if (type && site) {
            return this.serviceFeeSettings.value.filter(item => item.type === type && item.site === site)
        } else if (type) {
            return this.serviceFeeSettings.value.filter(item => item.type === type)
        } else if (site) {
            return this.serviceFeeSettings.value.filter(item => item.site === site)
        }
        return this.serviceFeeSettings.value
    }

    // 获取服务费率设置
    getServiceRateSettings(): ServiceRateSetting[] {
        return this.serviceRateSettings.value
    }

    // 获取保证金比例设置
    getDepositRateSettings(): DepositRateSetting[] {
        return this.depositRateSettings.value
    }

    // 根据金额获取手续费（B类客户）
    getServiceFeeForB(amount: number, site: string): number {
        const bSettings = this.getServiceFeeSettings('B', site)
        for (const setting of bSettings) {
            const min = setting.minAmount || 0
            const max = setting.maxAmount || Infinity
            if (amount >= min && amount <= max) {
                return setting.fee
            }
        }
        return 200 // 默认手续费
    }

    // 根据金额获取手续费（C类客户）
    getServiceFeeForC(amount: number, site: string): number {
        const cSettings = this.getServiceFeeSettings('C', site)
        for (const setting of cSettings) {
            const min = setting.minAmount || 0
            const max = setting.maxAmount || Infinity
            if (amount >= min && amount <= max) {
                return setting.fee
            }
        }
        return 100 // 默认手续费
    }

    // 获取默认服务费率
    getDefaultServiceRate(): number {
        const settings = this.getServiceRateSettings()
        if (settings.length > 0) {
            return settings[0].rate
        }
        return 3.5 // 默认服务费率
    }

    // 获取默认保证金比例
    getDefaultDepositRate(): number {
        const settings = this.getDepositRateSettings()
        if (settings.length > 0) {
            return settings[0].rate
        }
        return 10.0 // 默认保证金比例
    }

    // 添加手续费设置
    addServiceFeeSetting(setting: Omit<ServiceFeeSetting, 'id'>) {
        const newSetting: ServiceFeeSetting = {
            ...setting,
            id: `serviceFee_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
        }
        this.serviceFeeSettings.value.push(newSetting)
        this.saveToStorage()
    }

    // 更新手续费设置
    updateServiceFeeSetting(id: string, setting: Partial<ServiceFeeSetting>) {
        const index = this.serviceFeeSettings.value.findIndex(item => item.id === id)
        if (index !== -1) {
            this.serviceFeeSettings.value[index] = { ...this.serviceFeeSettings.value[index], ...setting }
            this.saveToStorage()
        }
    }

    // 删除手续费设置
    deleteServiceFeeSetting(id: string) {
        const index = this.serviceFeeSettings.value.findIndex(item => item.id === id)
        if (index !== -1) {
            this.serviceFeeSettings.value.splice(index, 1)
            this.saveToStorage()
        }
    }

    // 添加服务费率设置
    addServiceRateSetting(setting: Omit<ServiceRateSetting, 'id'>) {
        const newSetting: ServiceRateSetting = {
            ...setting,
            id: `serviceRate_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
        }
        this.serviceRateSettings.value.push(newSetting)
        this.saveToStorage()
    }

    // 更新服务费率设置
    updateServiceRateSetting(id: string, setting: Partial<ServiceRateSetting>) {
        const index = this.serviceRateSettings.value.findIndex(item => item.id === id)
        if (index !== -1) {
            this.serviceRateSettings.value[index] = { ...this.serviceRateSettings.value[index], ...setting }
            this.saveToStorage()
        }
    }

    // 删除服务费率设置
    deleteServiceRateSetting(id: string) {
        const index = this.serviceRateSettings.value.findIndex(item => item.id === id)
        if (index !== -1) {
            this.serviceRateSettings.value.splice(index, 1)
            this.saveToStorage()
        }
    }

    // 添加保证金比例设置
    addDepositRateSetting(setting: Omit<DepositRateSetting, 'id'>) {
        const newSetting: DepositRateSetting = {
            ...setting,
            id: `depositRate_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`
        }
        this.depositRateSettings.value.push(newSetting)
        this.saveToStorage()
    }

    // 更新保证金比例设置
    updateDepositRateSetting(id: string, setting: Partial<DepositRateSetting>) {
        const index = this.depositRateSettings.value.findIndex(item => item.id === id)
        if (index !== -1) {
            this.depositRateSettings.value[index] = { ...this.depositRateSettings.value[index], ...setting }
            this.saveToStorage()
        }
    }

    // 删除保证金比例设置
    deleteDepositRateSetting(id: string) {
        const index = this.depositRateSettings.value.findIndex(item => item.id === id)
        if (index !== -1) {
            this.depositRateSettings.value.splice(index, 1)
            this.saveToStorage()
        }
    }

    // 清除所有设置并重新初始化默认数据
    clearAllSettings() {
        // 清除localStorage中的数据
        localStorage.removeItem('baseSettings_serviceFees')
        localStorage.removeItem('baseSettings_serviceRates')
        localStorage.removeItem('baseSettings_depositRates')

        // 重新初始化默认数据
        this.init()
    }
}

// 创建全局基础设置服务实例
const baseSettingsService = new BaseSettingsService()

// 初始化服务
baseSettingsService.init()

// 导出服务实例
export { baseSettingsService }

// 默认导出
export default baseSettingsService 